package com.cls.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cls.business.entity.*;
import com.cls.business.mapper.*;
import com.cls.business.service.IReviewService;
import com.cls.business.vo.ExpertReviewResultVO;
import com.cls.common.entity.QueryRequest;
import com.cls.common.enums.DictEnum;
import com.cls.system.entity.Expert;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Service实现
 *
 * @author wandering
 * @date 2020-11-18 11:58:54
 */
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ReviewServiceImpl extends ServiceImpl<ReviewMapper, Review> implements IReviewService {

    private final ReviewDetailMapper reviewDetailMapper;

    private final ExpertGroupMapper expertGroupMapper;

    private final DeclareTopicMapper declareTopicMapper;

    private final DeclarePlanMapper declarePlanMapper;

    private final TopicPlanMapper topicPlanMapper;

    private final TopicMapper topicMapper;

    @Override
    public PageInfo<DeclareTopic> selectDeclareTopicView(QueryRequest request, Map<String, Object> params) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<DeclareTopic> list = baseMapper.selectDeclareTopicView(params);
        for (DeclareTopic one : list) {
            if (DictEnum.ENTRUST.getCode().equals(one.getTopicClassifyCode())) {
                DeclarePlan declarePlan = declarePlanMapper.findByDeclareTopicIdAndPlanId(one.getDeclareId(), one.getPlanId());
                if (declarePlan != null) {
                    one.setAchievementFormTypeCode(declarePlan.getAchievementFormTypeCode());
                }
            }
        }
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public PageInfo<DeclareTopic> findDeclareTopicsByPlanIDAndExpertId(QueryRequest request, Long planId, Long expertId) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<DeclareTopic> list = baseMapper.selectDeclareTopicByPlanIdAndExpertId(planId, expertId);
        for (DeclareTopic one : list) {
            Topic topic = topicMapper.selectById(one.getTopicId());
            if (topic != null) {
                one.setTopicName(topic.getTopicName());
            }
        }
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }


    @Override
    public List<Review> findReviews(Review review) {
        LambdaQueryWrapper<Review> queryWrapper = new LambdaQueryWrapper<>();
        // TODO 设置查询条件
        if (review.getDeclareId() != null) {
            queryWrapper.eq(Review::getDeclareId, review.getDeclareId());
        }
        if (review.getPlanId() != null) {
            queryWrapper.eq(Review::getPlanId, review.getPlanId());
        }
        if (review.getExpertId() != null) {
            queryWrapper.eq(Review::getExpertId, review.getExpertId());
        }
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public Review getAllList(Long reviewId) {
        Review review = this.baseMapper.selectById(reviewId);
        if (review == null) {
            return review;
        }
        Long planId = review.getPlanId();
        TopicPlan topicPlan = topicPlanMapper.selectById(planId);
        if (topicPlan == null) {
            return null;
        }

        //根据查询所有选项详情
        List<ReviewDetail> reviewDetails = reviewDetailMapper.findByStandardAndReviewId(topicPlan.getStandardId(), review.getReviewId());
       /* for (ReviewDetail item : reviewDetails) {
            if (item.getIsChoose() == null || !item.getIsChoose()) {
                item.setIsChoose(false);
            }
            item.setIndicatorGroupName(item.getIndicatorName() + " - " + item.getIndicatorDescription());
        }*/
        LinkedHashMap<String, List<ReviewDetail>> reviewDetailGroup = reviewDetails.stream().collect(Collectors.groupingBy(item -> {
            if (item.getIsChoose() == null || !item.getIsChoose()) {
                item.setIsChoose(false);
            }
            item.setIndicatorGroupName(item.getIndicatorName() + " - " + item.getIndicatorDescription());
            return item.getIndicatorGroupName();
        }, LinkedHashMap::new, Collectors.toList()));

//        Map<String, List<ReviewDetail>> reviewDetailGroup = reviewDetails.stream().collect(Collectors.groupingBy(ReviewDetail::getIndicatorGroupName));
        List<ReviewSubject> reviewSubjectList = new ArrayList<>();
        for (Map.Entry<String, List<ReviewDetail>> entry : reviewDetailGroup.entrySet()) {
            ReviewSubject reviewSubject = new ReviewSubject();

            String name = entry.getKey();
            reviewSubject.setIndicatorName(name);

            List<ReviewDetail> valuelist = entry.getValue();
            //排序
            List<ReviewDetail> listsSort = valuelist.stream().sorted(Comparator.comparing(ReviewDetail::getIndicatorType).reversed()).collect(Collectors.toList());
            ReviewDetail reviewDetailOne = listsSort.get(0);
            reviewSubject.setWeight(reviewDetailOne.getWeight());
            reviewSubject.setIndicatorDescription(reviewDetailOne.getIndicatorDescription());
            reviewSubject.setReviewDetailList(listsSort);
            reviewSubjectList.add(reviewSubject);
        }
        review.setReviewSubjectList(reviewSubjectList);
        return review;
    }


//    @Override
//    public Review getAllList(Long declareId, Long expertId) {
//        Review review=this.baseMapper.selectByDeclareIdAndExpertId(declareId,expertId);
//        if(review==null){
//            return review ;
//        }
//        //根据查询所有选项详情
//        System.out.println(review.getReviewId());
//        List<ReviewDetail> reviewDetails = reviewDetailService.findReviewDetailsByReviewId(review.getReviewId());
//        for (ReviewDetail item:reviewDetails) {
//            item.setIndicatorGroupName(item.getIndicatorName()+item.getIndicatorDescription());
//        }
//
//        Map<String, List<ReviewDetail>> reviewDetailGroup =reviewDetails.stream().collect(Collectors.groupingBy(ReviewDetail::getIndicatorGroupName));
//        List<ReviewSubject> reviewSubjectList=new ArrayList<>();
//        for (Map.Entry<String, List<ReviewDetail>> entry : reviewDetailGroup.entrySet()) {
//            ReviewSubject reviewSubject=new ReviewSubject();
//
//            String name = entry.getKey();
//            reviewSubject.setIndicatorName(name);
//
//            List<ReviewDetail> valuelist = entry.getValue();
//            //排序
//            List<ReviewDetail> listsSort = valuelist.stream().sorted(Comparator.comparing(ReviewDetail::getIndicatorType).reversed()).collect(Collectors.toList());
//            ReviewDetail reviewDetailOne = listsSort.get(0);
//            reviewSubject.setWeight(reviewDetailOne.getWeight());
//            reviewSubject.setIndicatorDescription(reviewDetailOne.getIndicatorDescription());
//            reviewSubject.setReviewDetailList(listsSort);
//            reviewSubjectList.add(reviewSubject);
//        }
//        review.setReviewSubjectList(reviewSubjectList);
//        return review;
//    }

    @Override
    public List<Review> findReviewsByDeclareIds(Set<Long> declareIds) {
        LambdaQueryWrapper<Review> queryWrapper = new LambdaQueryWrapper<>();
        // TODO 设置查询条件
        queryWrapper.in(Review::getDeclareId, declareIds);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createReview(Review review) {
        this.save(review);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateReview(Review review, Long expertId) {
        Review before = baseMapper.findByDeclareIdAndExpertId(review.getDeclareId(), review.getExpertId());
        if (before != null) {
            before.setExpertId(expertId);
        }
        this.saveOrUpdate(before);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateList(Review review) {
        //总分
        Double allScore = 0.0;
        //修改list里面选项
        List<ReviewSubject> reviewSubjectList = review.getReviewSubjectList();
        //所有打分选中项的list
        List<ReviewDetail> reviewDetailListAll = new ArrayList<>();
        for (ReviewSubject sub : reviewSubjectList) {
            List<ReviewDetail> reviewDetailList = sub.getReviewDetailList();
            for (ReviewDetail rde : reviewDetailList) {
                if (rde.getIsChoose()) {
                    //得分=打分*权重/100
                    Double score = rde.getScore() * rde.getWeight();
                    Double operationScore = score / 100;
                    allScore += operationScore;
                    ReviewDetail choose = new ReviewDetail();
                    choose.setScore(rde.getScore());
                    choose.setReviewId(review.getReviewId());
                    choose.setIndicatorDetailId(rde.getIndicatorDetailId());
                    choose.setIsChoose(true);
                    reviewDetailListAll.add(choose);
                }
            }
        }
        review.setScore(allScore);
        this.saveOrUpdate(review);
        //删除所有选项表  根据reviewId
        reviewDetailMapper.deleteForReviewId(review.getReviewId());
        //新增选择项
        reviewDetailListAll.forEach(reviewDetail ->
                this.reviewDetailMapper.insert(reviewDetail)
        );
    }


    /**
     * 删除
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteReviews(String[] ids) {
        List<String> list = Arrays.asList(ids);
        this.removeByIds(list);
    }

    /**
     * wmm
     * 根据Long declareId查询所有的专家
     *
     * @param declareId
     * @return
     */
    @Override
    public List<Expert> selectExpertByDeclareId(Long declareId, Long planId) {
        return this.baseMapper.selectExpertByDeclareId(declareId, planId);
    }

    /**
     * 魏起成
     * 根据申请课题id查询专家评审结果
     *
     * @param declareId
     * @return
     */
    @Override
    public List<Map<String, Object>> selectResultByDeclareId(Long declareId, Long planId) {
        List<Expert> experts = this.baseMapper.selectExpertByDeclareId(declareId, planId);
        //查询所有的评审结果
        List<Map<String, Object>> maps = this.baseMapper.selectResultByDeclareId(declareId, experts, planId);
        //添加评审意见
        List<Review> reviewList = this.baseMapper.selectByDeclareId(declareId);
        Map<String, Object> optionMap = new HashMap<>();
        optionMap.put("indicatorName", "专家评审意见");
        //添加专家得分
        Map<String, Object> sorceMap = new HashMap<>();
        sorceMap.put("indicatorName", "得分");
        reviewList.forEach(item -> {
            optionMap.put(item.getExpertId().toString(), item.getOpinion());
            sorceMap.put(item.getExpertId().toString(), item.getScore());
        });
        maps.add(optionMap);
        maps.add(sorceMap);
        return maps;
    }

    @Override
    @Transactional
    public boolean createReviewData(List<ExpertGroup> groups) {
//        List<ReviewDetail> createDetails = new ArrayList();
        for (ExpertGroup one : groups) {
            expertGroupMapper.insert(one);
            List<Review> reviews = one.getReviews();
            for (Review review : reviews) {
                review.setGroupId(one.getExpertGroupId());
                baseMapper.insert(review);
//                List<ReviewDetail> details = indicatorMapper.getReviewDetailTemplate();
//                for(ReviewDetail detail:details){
//                    detail.setReviewId(review.getReviewId());
//                    createDetails.add(detail);
//                }
            }
        }
//        if(createDetails.size() > 0){
//            reviewDetailService.saveBatch(createDetails);
//        }
        return true;
    }

    @Override
    @Transactional
    public boolean submitReview(Review review, DeclareTopic declareTopic, DeclarePlan declarePlan) {
        if (review != null) {
            baseMapper.updateById(review);
        }

        if (declareTopic != null) {
            declareTopicMapper.updateById(declareTopic);
        }

        if (declarePlan != null) {
            DeclarePlan existDeclarePlan = declarePlanMapper.findByDeclareTopicIdAndPlanId(declarePlan.getDeclareId(), declarePlan.getPlanId());
            if (existDeclarePlan != null) {
                existDeclarePlan.setPlanScore(declarePlan.getPlanScore());
                declarePlanMapper.updateById(existDeclarePlan);
            }
        }
        return true;
    }

    @Override
    public PageInfo<ReviewDetail> getSoureLogById(QueryRequest request, Long reviewId) {

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<ReviewDetail> reviewDetailList = reviewDetailMapper.getByReviewIdList(reviewId);
        reviewDetailList.forEach(item -> {
            item.setIndicatorGroupName(item.getIndicatorName() + item.getIndicatorDescription());
        });
        PageInfo pageInfo = new PageInfo(reviewDetailList);
        return pageInfo;
    }


    @Override
    public List<ExpertReviewResultVO> selectReviewByPlanIdAndStandardId(Long planId, Long standardId) {
        return baseMapper.selectReviewByPlanIdAndStandardId(planId, standardId);
    }

}
